package com.yantu.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.*;
import com.yantu.mapper.*;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.admin.AdminPageView;
import com.yantu.view.admin.markPaper.PaperView;
import com.yantu.view.admin.markPaper.ScoreView;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-15
 */
@RestController
@RequestMapping("/admin")
@ApiModel("管理端答卷接口")
public class AdminExamPaperAnswerController extends AdminUserEventLogController{

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ExamPaperAnswerMapper examPaperAnswerMapper;

    @Autowired
    ExamPaperQuestionCustomerAnswerMapper examPaperQuestionCustomerAnswerMapper;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    TextContentMapper textContentMapper;

    @Autowired
    ExamPaperMapper examPaperMapper;

    //答卷分页
    @GetMapping("/examPaperAnswer")
    @ApiOperation("答卷分页信息")
    public Result myExamPaperAnswer(@ModelAttribute AdminPageView pageView){
        PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
        if(redisUtils.haskeysf("adminExamPaperAnswers"+pageView)) {
            System.out.println("缓存里面有");
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("adminExamPaperAnswers"+pageView);
            return Result.succ(200, "查询成功", pageInfo);
        }else {
            QueryWrapper<ExamPaperAnswer> queryWrapper = new QueryWrapper<>();
            if (pageView.getSubjectId() != null) {
                queryWrapper.eq("subject_id", pageView.getSubjectId());
            }
            List<ExamPaperAnswer> examPaperAnswersList = examPaperAnswerMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo(examPaperAnswersList);
            redisUtils.saveValue("adminExamPaperAnswers"+pageView,pageInfo);
            return Result.succ(200, "查询成功", pageInfo);
        }
    }
    //答卷内容
    @GetMapping("/examPaperAnswerContent/{id}")
    @ApiOperation("答卷内容")
    public Result examPaperAnswerContent(@PathVariable("id") Integer id) {
        if(redisUtils.haskeysf("adminExamPaperAnswerContent"+id)) {
            System.out.println("缓存里面有");
             Map map = (Map) redisUtils.getValue("adminExamPaperAnswerContent"+id);
            return Result.succ(200, "查询成功", map);
        }else {
            //获取答题卡
            ExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectById(id);
            //获取试卷信息
            ExamPaper examPaper = examPaperMapper.selectById(examPaperAnswer.getExamPaperId());
            //答题内容Map
            HashMap<String, Object> answerMap = new HashMap<>();
            answerMap.put("id", id);
            //去textcontent里面找titleItems(获取试卷的TextContent)
            TextContent textContent = textContentMapper.selectById(examPaper.getFrameTextContentId());
            System.out.println("这是试卷的对应的TextContent（id,content）");
            System.out.println(textContent);
            JSONArray contentArray = JSONArray.fromObject(textContent.getContent());
            System.out.println("这是试卷的对应的TextContent的content内容");
            System.out.println(contentArray);
            List<Object> bigQuestionList = new ArrayList<>();
            for (int j = 0; j < contentArray.size(); j++) {
                //获取第i个大题的题目列表
                JSONObject content = contentArray.getJSONObject(j);
                System.out.println("是大题内题目列表吗? eg:{\"name\":\"单选题\",\"questionItems\":[{\"id\":34,\"itemOrder\":1},{\"id\":31,\"itemOrder\":2}]}");
                System.out.println(content);
                Map bigQuestionMap = new HashMap<>();
                bigQuestionMap.put("name", content.getString("name"));
                //将一个大题内的小题列表转换为json数组
                JSONArray questionItemArray = JSONArray.fromObject(content.getString("questionItems"));
                List<Object> smallQuestionList = new ArrayList<>();
                //获取小题列表里的每一个问题
                for (int i = 0; i < questionItemArray.size(); i++) {
                    JSONObject question = questionItemArray.getJSONObject(i);
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("question_id", question.getInt("id"));
                    queryWrapper.eq("exam_paper_answer_id", id);
                    ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = examPaperQuestionCustomerAnswerMapper.selectOne(queryWrapper);
                    System.out.println("找到这个在exam_paper_question_customer表里面的内容了");
                    System.out.println(examPaperQuestionCustomerAnswer);
                    //开始获取学生的答案（回答）
                    Map smallMap = new HashMap<>();
                    smallMap.put("questionId", examPaperQuestionCustomerAnswer.getQuestionId());
                    //选择题学生答案
                    if (examPaperQuestionCustomerAnswer.getAnswer() != null) {
                        smallMap.put("answer", examPaperQuestionCustomerAnswer.getAnswer());
                    } else {
                        smallMap.put("answer", null);
                    }
                    //非选择题的学生答题内容
                    if (examPaperQuestionCustomerAnswer.getTextContentId() != null) {
                        System.out.println(examPaperQuestionCustomerAnswer.getTextContentId());
                        TextContent textContent1 = textContentMapper.selectById(examPaperQuestionCustomerAnswer.getTextContentId());
                        System.out.println(textContent1);
                        smallMap.put("answerContent", textContent1.getContent());
                    } else {
                        smallMap.put("answerContent", null);
                    }
                    smallQuestionList.add(smallMap);
                }
                bigQuestionMap.put("answerItems", smallQuestionList);
                System.out.println("获取到每一个大题里的小题的答案了");
                System.out.println(bigQuestionMap);
                bigQuestionList.add(bigQuestionMap);
            }
            answerMap.put("data", bigQuestionList);
            redisUtils.saveValue("adminExamPaperAnswerContent"+id,answerMap);
            return Result.succ(200, "查询成功", answerMap);
        }
    }

    //批改试卷
    @PutMapping("/examPaperAnswerContent")
    @ApiOperation("批阅试卷")
    public Result markPaper(@RequestBody PaperView paperView){
        //设置题目得分
        List<ScoreView> scoreViewList=paperView.getScoreViewList();
        //总分
        System.out.println(scoreViewList);
        int sum=0;
        int doRightCount=0;
        for (ScoreView scoreView:scoreViewList) {
            UpdateWrapper<ExamPaperQuestionCustomerAnswer> updateWrapper=new UpdateWrapper<>();
            updateWrapper.eq("exam_paper_answer_id",paperView.getId());
            updateWrapper.eq("question_id",scoreView.getQuestionId());
            updateWrapper.set("customer_score",scoreView.getCustomerScore());
            updateWrapper.set("do_right",scoreView.getDoRight());
            if(scoreView.getDoRight()==1){
                doRightCount=doRightCount+1;
            }
            sum=sum+scoreView.getCustomerScore();
            int result=examPaperQuestionCustomerAnswerMapper.update(null,updateWrapper);
        }
        UpdateWrapper<ExamPaperAnswer> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",paperView.getId());
        updateWrapper.set("user_score",sum);
        updateWrapper.set("question_correct",doRightCount);
        updateWrapper.set("status",2);
        int result=examPaperAnswerMapper.update(null,updateWrapper);
        if(result>0){
            UserEventLog userLog = new UserEventLog();
            userLog.setCreateTime(new Date());
            userLog.setUserName("admin");
            userLog.setRealName("管理员");
            userLog.setUserId(2);
            userLog.setContent("admin成功批阅试卷");
            super.adminLog("admin批阅了试卷"+paperView.getId());
            redisUtils.delAll();
            return Result.succ(200,"批阅成功",null);
        }else {
            return Result.fail("批阅失败");
        }
    }
}

